<template>
	<view class="fixedbody">
		<uni-forms ref="baseForm" :modelValue="baseFormData" label-width="80" :rules="rules">
			<view class="wBox">
				<view class="leftLine">基本信息</view>
				<view class="borderLine">
					 <uni-forms-item label="照片" name="picUrl" required>
					 	<view class="mt-15 mb-10 color01">(近期彩色免冠照片,尺寸200*280)</view>
					 	<view class="avatarUrl">
					 		
					 		<uni-file-picker v-model="baseFormData.picUrlObj"   :image-styles="imageStylespic"
					 			@delete="delpersonphoto" return-type="object" limit="1"
					 			@select="uppersonlogo">
					 			<view class="flexColumn uploadBox">
					 			<i class="iconfont icon-biaodanbianjitupianduoxuan"></i>
					 			<view>上传照片</view>
					 			</view>
					 		</uni-file-picker>
					 	</view>
					 </uni-forms-item>
					 <uni-forms-item label="姓名" required name="realName">
					 	<uni-easyinput v-model="baseFormData.realName" placeholder="请输入姓名" />
					 </uni-forms-item>
					 <uni-forms-item label="国籍" required name="countryId">
					 	<uni-data-select v-model="baseFormData.countryId" @change="changeCountryId"
					 		:localdata="countryList"></uni-data-select>
					 </uni-forms-item>
					 <uni-forms-item label="民族" required name="nation">
					 	<!-- <uni-easyinput v-model="baseFormData.nation" placeholder="请输入民族" /> -->
					 	<uni-data-select v-model="baseFormData.nation" :localdata="nationList"></uni-data-select>
					 </uni-forms-item>
					 
					 
					 <uni-forms-item label="证件类型" required name="idcType">
					 	<uni-data-select v-model="baseFormData.idcType" :localdata="idcTypeList"></uni-data-select>
					 </uni-forms-item>
					 <uni-forms-item label="证件号码" required name="idcCode">
					 	<uni-easyinput v-model="baseFormData.idcCode" type="idcard" placeholder="请输入证件号码"
					 		@blur="checkCode" />
					 </uni-forms-item>
					 <uni-forms-item label="性别" required name="sex">
					 	<uni-data-checkbox selectedColor="red" selectedTextColor="red" v-model="baseFormData.sex" :localdata="sexs" />
					 </uni-forms-item>
					 
					 <uni-forms-item label="出生日期" required name="birth">
					 	<uni-datetime-picker type="date" :clear-icon="false" v-model="baseFormData.birth" />
					 </uni-forms-item>
					 <uni-forms-item label="联系方式" name="phone" :required="showRequire">
					 	<uni-easyinput type="number" v-model="baseFormData.phone" placeholder="请输入联系方式" />
					 </uni-forms-item>
					 
					 <uni-forms-item label="所在地区">
					 	<uni-data-picker class="fixUniFormItemStyle" v-model="baseFormData.regionId"
					 		:localdata="regionsList" popup-title="请选择所在地区"></uni-data-picker>
					 </uni-forms-item>
					 <uni-forms-item label="详细地址"><uni-easyinput v-model="baseFormData.address"
					 		placeholder="请输入详细地址" /></uni-forms-item>
					 
					 <uni-forms-item label="身份标签" required name="label">
					 	<uni-data-checkbox selectedColor="red" selectedTextColor="red" @change="labelChange" v-model="baseFormData.labelArr" multiple
					 		:localdata="tagList" />
					 </uni-forms-item>
				</view>
				
			</view>

			
			<view class="wBox">
				<view class="gapTitle leftLine">
					实名认证
					<text>正面为国徽面 反面为头像面</text>
				</view>
				<view class="borderLine">
				<view class="ttt">
					头像面<text>请拍摄完整身份证</text>
				</view>
				<view class="idImgUrl">
					<uni-file-picker v-model="baseFormData.idcFrontImgObj" @delete="delimgFont" return-type="object"
						limit="1" @select="upIdCardImgFront" :image-styles="imageStyles">
						<div class="sfz">
							 <image src="../../static/zm.png"></image>
						</div>
						
						</uni-file-picker>
					<!-- 					<button type="balanced" open-type="chooseAvatar" @chooseavatar="upIdCardImgFront">
						<image mode="aspectFill" :src="baseFormData.idcFrontImg" class="idImg"></image>
					</button>
 -->
				</view>

				<view class="ttt">
					国徽面<text>请拍摄完整身份证</text>
				</view>
				<view class="idImgUrl">
					<uni-file-picker limit="1" v-model="baseFormData.idcBackImgObj" @delete="delimgBack"
						return-type="object" @select="upIdCardImgBack" :image-styles="imageStyles">
						  <div class="sfz">
						  	 <image src="../../static/bm.png"></image>
						  </div>
						</uni-file-picker>
					<!-- 					<button type="balanced" open-type="chooseAvatar" @chooseavatar="upIdCardImgBack">
						<image mode="aspectFill" :src="baseFormData.idcBackImg" class="idImg"></image>
					</button>
 -->
				</view>
                </view>
			</view>
			<view class="wBox">
			<view class="leftLine">紧急联系方式</view>
			<view class="borderLine">
				 <uni-forms-item label="紧急联系人" label-width="110"><uni-easyinput v-model="baseFormData.ecName"
				 		placeholder="请输入联系人" /></uni-forms-item>
				 <uni-forms-item label="紧急联系方式" label-width="110"><uni-easyinput v-model="baseFormData.ecPhone" type="number"
				 		placeholder="请输入联系方式" /></uni-forms-item>
				 <uni-forms-item label="与本人关系" label-width="110"><uni-easyinput v-model="baseFormData.ecRelationship"
				 		placeholder="请输入与本人关系" /></uni-forms-item>
			</view>
			</view>
		</uni-forms>

		<view class="fixedBottom"><button class="btn btn1" @click="add('baseForm')" type="default">确定</button></view>
	</view>
</template>

<script setup>
	import {
		reactive,
		toRefs,
		ref,
		getCurrentInstance
	} from 'vue';
	import * as match from '@/common/match.js';
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app';
	import {
		sexs,
		idcTypeList,
		nationList
	} from '@/static/js/data'
	import config from '@/config.js'
	const {
		proxy
	} = getCurrentInstance()
	const data = reactive({
		baseFormData: {
			countryId: 240
		},
		groupId: '',
		countryList: [],
		tagList: [{
			text: '运动员',
			value: '0'
		}, {
			text: '教练',
			value: '1'
		}, {
			text: '领队',
			value: '2'
		}, {
			text: '队医',
			value: '4'
		}, {
			text: '翻译',
			value: '5'
		}, {
			text: '官员',
			value: '6'
		}, {
			text: '其他',
			value: '3'
		}],
		regionsList: [],
		rules: {
			realName: {
				rules: [{
					required: true,
					errorMessage: '必填项'
				}]
			},
			countryId: {
				rules: [{
					required: true,
					errorMessage: '必填项'
				}]
			},
			nation: {
				rules: [{
					required: true,
					errorMessage: '必填项'
				}]
			},
			idcType: {
				rules: [{
					required: true,
					errorMessage: '必填项'
				}]
			},
			idcCode: {
				rules: [{
					required: true,
					errorMessage: '必填项'
				}]
			},
			sex: {
				rules: [{
					required: true,
					errorMessage: '必填项'
				}]
			},
			birth: {
				rules: [{
					required: true,
					errorMessage: '必填项'
				}]
			},
			label: {
				rules: [{
					required: true,
					errorMessage: '必填项'
				}]
			}
		},
		signType: '',
		showRequire:false
	});
	const {
		baseFormData,
		groupId,
		countryList,
		regionsList,
		rules,
		signType,
		tagList,showRequire
	} = toRefs(data);
	const imageStylespic=ref({width:'200rpx',height:'280rpx',border:{radius:'2px'}});
	const imageStyles = ref({
		width: '500rpx',
		height: '300rpx',
		border: {
			radius: '2px'
		}
	});
	let editgay = false
	let platform = ''
	onLoad(option => {
		getCountryList()
		getRegionsList()
		console.log(option)
		if (option.groupId != '0') {
			groupId.value = option.groupId
			if (option.id == '0') {
				// 团队成员-新建
				baseFormData.value.groupId = groupId.value
			}
		}
		if (option.id != '0') {
			// 编辑修改-先获取信息
			editgay = true
			match.getPersonInfoById(option.id).then(res => {
				baseFormData.value = res.data;
				baseFormData.value.id = option.id
				if (baseFormData.value.idcFrontImg) {
					baseFormData.value.idcFrontImgObj = {
						name: "正面",
						extname: "jpg",
						url: baseFormData.value.idcFrontImg,
					}
				}
				if (baseFormData.value.idcBackImg) {
					baseFormData.value.idcBackImgObj = {
						name: "反面",
						extname: "jpg",
						url: baseFormData.value.idcBackImg,
					}
				}
				if(baseFormData.value.picUrl){
					baseFormData.value.picUrlObj = {
						name:"head",
						extname:"jpg",
						url:baseFormData.value.picUrl,
					}
				}
				
				if (baseFormData.value.label != null) {
					// {0:0,1:1,2:3}
					baseFormData.value.labelArr = baseFormData.value.label.split(',')
					if (baseFormData.value.labelArr.indexOf('1') > -1 || baseFormData.value.labelArr.indexOf('2') > -1) {
					  // 联系方式必填
					  showRequire.value = true
					} else {
					  showRequire.value = false
					}
				}
			});
		}
		if (option.signType) {
			signType.value = option.signType
		}
		wx.getSystemInfo({
		  success: (res) => {
		  	// windows | mac为pc端
			if(res.platform=='windows'||res.platform=='mac'||res.platform=='devtools'){
				platform = 'pc'
			}
		  }
		});
		// if(option.noAthletes==1){
		// 	tagList.value = [{text: '教练',value: '1'},{text: '领队',value: '2'},{text: '队医',value: '4'},{text: '翻译',value: '5'},{text: '官员',value: '6'},{text: '其他',value: '3'}]
		// }

	});
function delpersonphoto(){
	baseFormData.value.picUrl = '';
}
function uppersonlogo(e){
	console.log(e,platform)
	const tempFilePaths = e.tempFilePaths;
	const imgUrl=tempFilePaths[0]
	if(platform == 'pc'){
		uni.showLoading({
			title: '加载中'
		});
		uni.uploadFile({
			url: config.baseUrl_api + '/upload/uploadImg',
			filePath: imgUrl,
			name: 'image'
		}).then(res => {
			let data = JSON.parse(res.data);
			baseFormData.value.picUrl = data.data;
		}).finally(()=>{
			uni.hideLoading();
		});
	}else{
		console.log(111)
		wx.cropImage({
			src: imgUrl,
			cropScale: '3:4',
			success: function(resp){
				console.log(resp)
				uni.showLoading({
					title: '加载中'
				});
				uni.uploadFile({
					url: config.baseUrl_api + '/upload/uploadImg',
					filePath: resp.tempFilePath,
					name: 'image'
				}).then(res => {
						let data = JSON.parse(res.data);
						console.log(1,data)
						baseFormData.value.picUrl = data.data;
						console.log(2,baseFormData.value.picUrl)
				}).finally(()=>{
					uni.hideLoading();
				});
				
			},
			fail: function(){
				baseFormData.value.picUrl = '';
			}
		})
	}
}

	function labelChange(e) {
		console.log(e.detail.value)
		  if (e.detail.value.indexOf('1') > -1 || e.detail.value.indexOf('2') > -1) {
		    // 联系方式必填
		    showRequire.value = true
		  } else {
		    showRequire.value = false
		  }
	}

	function getCountryList() {
		match.countryList().then(res => {
			countryList.value = res.data
			for (const c of countryList.value) {
				c.value = c.id
				c.text = c.name
			}
		})
	}

	function changeCountryId(e) {
		if (e != 240) {
			baseFormData.value.nation = '其他'
		}
	}

	function getRegionsList() {
		match.regionsList().then(res => {
			regionsList.value = res.data
		});
	}

	function checkCode() {
		if (baseFormData.value.idcType && baseFormData.value.idcCode) {
			// 验证是否存在这个人,如果有取过来
			var obj = {
				idcType: baseFormData.value.idcType,
				idcCode: baseFormData.value.idcCode
			}

			giveBirthDay()

			match.checkPerson(obj).then(res => {
				if (res.data.idcCode != null) {
					baseFormData.value = res.data
					if (baseFormData.value.idcFrontImg) {
						baseFormData.value.idcFrontImgObj = {
							name: "正面",
							extname: "jpg",
							url: baseFormData.value.idcFrontImg,
						}
					}
					if (baseFormData.value.idcBackImg) {
						baseFormData.value.idcBackImgObj = {
							name: "反面",
							extname: "jpg",
							url: baseFormData.value.idcBackImg,
						}
					}
					if (baseFormData.value.label != null) {
						baseFormData.value.labelArr = baseFormData.value.label.split(',')
						if (baseFormData.value.labelArr.indexOf('1') > -1 || baseFormData.value.labelArr.indexOf('2') > -1) {
						  // 联系方式必填
						  showRequire.value = true
						} else {
						  showRequire.value = false
						}
					}
					baseFormData.value.groupId = groupId.value
				}
			})
		}
	}

	function checkFormRequired(form) {
		proxy.$refs[form].validate().then(res => {
			console.log('通过')
		}).catch(err => {
			console.log('err', err);
		})
	}

	function giveBirthDay() {
		// 判断身份证正确性/赋值生日
		if (baseFormData.value.idcType == 0) {
			if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(baseFormData.value.idcCode))) {
				uni.showToast({
					title: '请输入正确的身份证号码',
					duration: 2000,
					icon: 'none'
				})
			} else {
				let tmpStr = "";
				if (baseFormData.value.idcCode.length == 15) {
					tmpStr = baseFormData.value.idcCode.substring(6, 12);
					tmpStr = "19" + tmpStr;
					tmpStr = tmpStr.substring(0, 4) + "-" + tmpStr.substring(4, 6) + "-" + tmpStr.substring(6)

				} else {
					tmpStr = baseFormData.value.idcCode.substring(6, 14);
					tmpStr = tmpStr.substring(0, 4) + "-" + tmpStr.substring(4, 6) + "-" + tmpStr.substring(6)

				}

				baseFormData.value.birth = tmpStr
				const res = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/
				if (baseFormData.value.idcCode && res.test(baseFormData.value.idcCode)) {
					const genderCode = baseFormData.value.idcCode.charAt(16)
					if (parseInt(genderCode) % 2 == 0) {
						baseFormData.value.sex = '0'
					} else {
						baseFormData.value.sex = '1'
					}
				}
			}
		}
	}

	function add(form) {
		// 添加后返回
		// checkFormRequired(form)
		if (!baseFormData.value.picUrl||baseFormData.value.picUrl == "") {
			uni.showToast({
				title: '请上传照片',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.realName == null) {
			uni.showToast({
				title: '请填写姓名',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.countryId == null) {
			uni.showToast({
				title: '请选择国籍',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.nation == null) {
			uni.showToast({
				title: '请填写民族',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.idcType == null) {
			uni.showToast({
				title: '请选择证件类型',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.idcCode == null) {
			uni.showToast({
				title: '请填写证件号码',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		// 验证身份证号
		if (baseFormData.value.idcType == 0 && !(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(baseFormData.value.idcCode))) {
			uni.showToast({
				title: '请输入正确的身份证号码',
				duration: 2000,
				icon: 'none'
			})
			return
		}

		if (baseFormData.value.sex == null) {
			uni.showToast({
				title: '请选择性别',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (baseFormData.value.birth == null) {
			uni.showToast({
				title: '请选择出生日期',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		// 验证手机号
		if(showRequire.value){
			var pattern = /^1[345789]\d{9}$/;
			if (!pattern.test(baseFormData.value.phone)) {  
				uni.showToast({
					title: '请输入正确的手机号',
					duration: 2000,
					icon: 'none'
				})
			    return   
			}   
		}

		if (baseFormData.value.labelArr == null || baseFormData.value.labelArr == []) {
			uni.showToast({
				title: '请选择身份标签',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		baseFormData.value.label = baseFormData.value.labelArr.toString()
		if (groupId.value && groupId.value != '0') {
			// 团队
			match.savePersonForMyGroup(baseFormData.value).then(res => {
				uni.showToast({
					title: '保存成功',
					duration: 2000,
					complete: () => {
						// 回到choose_coach /teamInfo /myInfo
						uni.navigateBack()
					}
				})
			})
		} else {
			if (editgay) {
				match.editPersonInfo(baseFormData.value).then(res => {
					uni.showToast({
						title: '保存成功',
						duration: 2000,
						complete: () => {
							uni.navigateBack()
						}
					})
				})
			} else {
				//个人
				match.savePersonForMyPerson(baseFormData.value).then(res => {
					uni.showToast({
						title: '保存成功',
						duration: 2000,
						complete: () => {
							uni.navigateBack()
						}
					})
				})
			}
		}
	}

	function onChooseavatar(e) {
		match.uploadFile(e).then(data => {
			baseFormData.value.picUrl = data.data;
		});
	}

	function upIdCardImgFront(e) {
		match.uploadImg(e).then(data => {
			baseFormData.value.idcFrontImg = data.data;
		});
	}

	function upIdCardImgBack(e) {
		match.uploadImg(e).then(data => {
			baseFormData.value.idcFrontImg = data.data;
		});
	}

	function delimgFont(n) {
		baseFormData.value.idcFrontImg = '';
	}

	function delimgBack(n) {
		baseFormData.value.idcBackImg = '';
	}
</script>

<style scoped lang="scss">
	.wBox {
		width: 700rpx;
		margin: 30rpx auto 0;
		padding: 30rpx 30rpx 1rpx;
	}

	.avatarUrl {
		width: 200rpx;
		height: 280rpx;
	}

	.avatarUrl button {
		padding: 0;
		display: block;
		line-height: 1;
	}

	.refreshIcon {
		width: 200rpx;
		height: 280rpx;
	}

	.ttt {
		color: #2B3133;
		font-size: 30rpx;
		margin: 0 0 10rpx;

		text {
			font-size: 24rpx;
			color: #DC0032;
			margin-left: 10rpx;
		}
	}

	.idImgUrl {
		width: 500rpx;
		height: 300rpx;
		margin: 20rpx auto 40rpx;

		button {
			padding: 0;
			display: block;
			line-height: 1;
		}

		.idImg {
			width: 500rpx;
			height: 300rpx;
		}
	}
	:deep(.file-picker__box-content){
		background:#f5f5f5d9;
	}
	.uploadBox{
		.iconfont{
			font-size:40px;
			color:#868484;
		}
		view{
			font-size:14px;
			color:#969090;
			margin-top:10rpx;
		}
	}
	.sfz{
		display: flex;
		justify-content: center;
		align-items: centr;
		border:1px dashed #ddd;
		border-radius:15rpx;
		image{
			width:250rpx;
			height:150rpx;
		}
	}
	:deep(.uni-data-checklist .checklist-group .checklist-box){
		min-width:140rpx;
	}
</style>